package com.wholesale.utils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.wholesale.R;
import com.wholesale.beans.CartInfo;
import com.wholesale.datas.DbHelperAdapter;
import com.wholesale.datas.ShopCar;
import com.wholesale.utils.AsyncImageLoader.ImageCallback;

public class CartListAdapter extends BaseAdapter {

	// ListView中的数据来源
	private final List<ShopCar> cartInfoList = new ArrayList<ShopCar>();
	private ListView listView;
	private AsyncImageLoader loader;
	private boolean isAsyncLoadData;
	private LinearLayout loadingLayout;
	private boolean isDelete = false;
	private TextView totalNumView;
	private TextView totalPriceView;

	private int lastItem;
	private Context context;

	public CartListAdapter(Context context, ListView listView) {
		// super(context, 0);
		this.context = context;
		this.listView = listView;
		loader = AsyncImageLoader.getInstance();
	}

	public CartListAdapter(Context context, List<ShopCar> catInfoList,
			ListView listView) {
		// super(context, 0, catInfoList);
		this.context = context;
		this.listView = listView;
		loader = AsyncImageLoader.getInstance();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		Activity activity = (Activity) context;

		// Inflate the views from XML
		View rowView = convertView;
		CartCache viewCache;
		if (rowView == null) {
			LayoutInflater inflater = activity.getLayoutInflater();
			rowView = inflater.inflate(R.layout.cartitems, null);
			viewCache = new CartCache(rowView);
			rowView.setTag(viewCache);
		} else {
			viewCache = (CartCache) rowView.getTag();
		}
		ShopCar shopCar = (ShopCar) getItem(position);
		CartInfo cartInfo = shopCar.getCartInfo();

		// Load the image and set it on the ImageView
		String imageUrl = cartInfo.getGoodsImg();
		ImageView imageView = viewCache.getGoodsImage();
		imageView.setTag(imageUrl);
		Drawable cachedImage = loader.loadDrawable(imageUrl,
				new ImageCallback() {
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl) {
						ImageView imageViewByTag = (ImageView) listView
								.findViewWithTag(imageUrl);
						if (imageViewByTag != null) {
							imageViewByTag.setBackgroundDrawable(imageDrawable);
						}
					}
				});
		if (cachedImage == null) {
			imageView.setBackgroundResource(R.drawable.loading);
		} else {
			imageView.setBackgroundDrawable(cachedImage);
		}
		// Set the text on the TextView
		if (isDelete) {
			viewCache.getGoodsNumber().setVisibility(View.GONE);
			viewCache.getGoodsNumberEdit().setVisibility(View.VISIBLE);
			// if(changeMap.get(shopCar.getGoodsId()) == null){
			// changeMap.put(shopCar.getGoodsId(), new
			// GoodsNumberEditWatcher(position, viewCache
			// .getTotalPrice()));
			// }
			// viewCache.getGoodsNumberEdit().addTextChangedListener(
			// changeMap.get(shopCar.getGoodsId()));
			viewCache.getGoodsNumberEdit().addTextChangedListener(
					new GoodsNumberEditWatcher(position, viewCache
							.getTotalPrice()));
			// viewCache.getGoodsNumberEdit().setOnFocusChangeListener(
			// new GoodsNumberEditListener(position, viewCache
			// .getTotalPrice()));
			viewCache.getDeteleButton().setTag(cartInfo.getGoodsId());
			viewCache.getDeteleButton().setVisibility(View.VISIBLE);
			viewCache.getDeteleButton().setOnClickListener(
					new lvButtonListener(position));
		} else {
			viewCache.getGoodsNumber().setVisibility(View.VISIBLE);
			viewCache.getGoodsNumberEdit().setVisibility(View.GONE);
			viewCache.getDeteleButton().setVisibility(View.GONE);
			viewCache.getDeteleButton().setOnClickListener(null);
		}
		String goodsAttr = cartInfo.getGoodsAttr();
		goodsAttr = goodsAttr.replaceAll(" ", "\n");
		goodsAttr = goodsAttr.replaceAll(",", "\n");
		viewCache.getAttributeTextView().setText(goodsAttr);

		// 老代码
		// if (goodsAttr != null && !goodsAttr.equals("")) {
		// String[] strs = goodsAttr.split("\n");
		// if (strs.length > 0) {
		// viewCache.getGoodsColorLable().setText(
		// strs[0].split(":")[0] + ":");
		// viewCache.getGoodsColor().setText(strs[0].split(":")[1]);
		// }
		// if (strs.length > 1) {
		// viewCache.getLadySizeLable().setText(
		// strs[1].split(":")[0] + ":");
		// viewCache.getLadySize().setText(strs[1].split(":")[1]);
		// }
		// }
		viewCache.getGoodsName().setText(cartInfo.getGoodsName());
		viewCache.getGoodsPrice().setText("" + cartInfo.getGoodsPrice());
		viewCache.getGoodsNumber().setText("" + cartInfo.getGoodsNumber());
		viewCache.getGoodsNumberEdit().setText("" + cartInfo.getGoodsNumber());
		viewCache.getTotalPrice().setText(
				""
						+ getTwoDecimal(cartInfo.getGoodsPrice()
								* cartInfo.getGoodsNumber()));
		return rowView;
	}

	public void setAsyncLoadData(boolean asyncLoadData) {
		this.isAsyncLoadData = asyncLoadData;
		getLoadView();
		this.listView.setOnScrollListener(scrollListener);
	}

	private void getLoadView() {
		if (loadingLayout == null) {
			LinearLayout searchLayout = new LinearLayout(context);
			searchLayout.setOrientation(LinearLayout.HORIZONTAL);
			ProgressBar progressBar = new ProgressBar(context);
			progressBar.setPadding(0, 0, 15, 0);
			searchLayout.addView(progressBar, new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.FILL_PARENT,
					LinearLayout.LayoutParams.FILL_PARENT));
			searchLayout.setGravity(Gravity.CENTER);

			TextView loadView = new TextView(context);
			loadView.setText("Loading......");
			loadView.setGravity(Gravity.CENTER);
			loadView.setTextSize((float) 16.0);
			loadView.setTextColor(Color.BLACK);
			loadingLayout = new LinearLayout(context);
			loadingLayout
					.setBackgroundResource(R.drawable.categories_cell_bg_on);
			// loadingLayout.addView(searchLayout, new
			// LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
			// LinearLayout.LayoutParams.WRAP_CONTENT));
			loadingLayout.addView(loadView, new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT));
			loadingLayout.setGravity(Gravity.CENTER);
		}
	}

	public void setDelete(boolean Delete) {
		isDelete = Delete;
	}

	OnScrollListener scrollListener = new OnScrollListener() {

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			lastItem = firstVisibleItem + visibleItemCount - 1;
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			if (lastItem == getCount()
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				loadingLayout.setVisibility(View.VISIBLE);
				listView.addFooterView(loadingLayout);
				Thread d = new Thread(new Runnable() {
					public void run() {
						// TODO Auto-generated method stub
						try {
							Thread.sleep(1500);
							mHandler.sendMessage(mHandler.obtainMessage());
						} catch (InterruptedException e) {
						}
					}
				});
				d.start();
			}
		}

	};

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// cartInfoList = WebServiceClient.getCartInfos();
			addItems(cartInfoList);
			loadingLayout.setVisibility(View.VISIBLE);
			listView.removeFooterView(loadingLayout);
		}
	};

	public void clear() {
		cartInfoList.clear();
	}

	/**
	 * 批量添加数据
	 * 
	 * @param items
	 */
	public void addItems(List<ShopCar> items) {
		for (ShopCar shopCar : items) {
			// this.add(shopCar);
			cartInfoList.add(shopCar);
		}
	}

	public void setTotalView(final TextView totalNumView,
			final TextView totalPriceView) {
		this.totalNumView = totalNumView;
		this.totalPriceView = totalPriceView;
	}

	class DeleteFavoriteListAsync extends AsyncTask<ShopCar, Integer, Boolean> {
		ProgressDialog pdialog;
		int position;

		public DeleteFavoriteListAsync(Context context, int position) {
			pdialog = new ProgressDialog(context);
			this.position = position;
			pdialog.setTitle("Deleteing...");
			pdialog.setMessage("Please wait...");
			pdialog.setCancelable(true);
			pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
					dialog.cancel();
					DeleteFavoriteListAsync.this.cancel(true);
				}
			});
			pdialog.show();
		}

		@Override
		protected Boolean doInBackground(ShopCar... params) {
			Boolean result = false;
			DbHelperAdapter dbHelperAdapter = new DbHelperAdapter(
					CartListAdapter.this.context);
			dbHelperAdapter.open();
			result = dbHelperAdapter.delete(params[0]);
			dbHelperAdapter.close();
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				ShopCar shopCar = (ShopCar) CartListAdapter.this
						.getItem(position);
				int num = Integer.parseInt(totalNumView.getText().toString()
						.trim());
				num = num - shopCar.getCartInfo().getGoodsNumber();
				totalNumView.setText("" + num);
				double price = Double.parseDouble(totalPriceView.getText()
						.toString().trim());
				price = price - shopCar.getCartInfo().getGoodsPrice()
						* shopCar.getCartInfo().getGoodsNumber();

				totalPriceView.setText("" + getTwoDecimal(price));
				// CartListAdapter.this.remove(CartListAdapter.this
				// .getItem(position));
				cartInfoList.remove(position);

				Intent myIntent = new Intent();// 创建Intent对象
				myIntent.setAction("com.wholesale.utils.UpdateUIService");
				myIntent.putExtra("cmd", Constants.CMD_DELETECAR_SERVICE);
				myIntent.putExtra("from", "com.wholesale.utils.CartListAdapter");
				((Activity) context).sendBroadcast(myIntent);
			} else {
				AlertDialog.Builder builder = new Builder(
						CartListAdapter.this.context);
				builder.setTitle("Error");
				builder.setMessage("Delete fail ");
				builder.setPositiveButton("Confirm",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();
			}
			pdialog.dismiss();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	class GoodsNumberEditWatcher implements TextWatcher {
		private int position;
		private int temp;
		private int beforeText;
		private int afterText;
		private ShopCar shopCar;
		private TextView curTotal;

		GoodsNumberEditWatcher(int pos, final TextView total) {
			position = pos;
			this.curTotal = total;
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			if (s.toString().equals("")) {
				temp = 0;
			} else {
				temp = Integer.parseInt(s.toString());
			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			if (s.toString().equals("")) {
				beforeText = 0;
			} else {
				beforeText = Integer.parseInt(s.toString());
			}
		}

		public void afterTextChanged(Editable s) {
			int now = 0;
			if (!s.toString().equals("")) {
				now = Integer.parseInt(s.toString().trim());
			} else {
				s.clear();
				s.append("0");
			}
			if (cartInfoList.get(position).getCartInfo().getGoodsNumber() != now
					&& isDelete) {
				int before = beforeText;
				// CartListAdapter.this.getItem(position).getCartInfo()
				// .setGoodsNumber(temp);
				cartInfoList.get(position).getCartInfo().setGoodsNumber(now);
				double price = cartInfoList.get(position).getCartInfo()
						.getGoodsPrice();
				int totalNum = Integer.parseInt(totalNumView.getText()
						.toString().trim());
				totalNum = totalNum - before + now;
				double totalPri = Double.parseDouble(totalPriceView.getText()
						.toString().trim());
				totalPri = totalPri + (now - before) * price;
				totalNumView.setText("" + totalNum);
				totalNumView.postInvalidate();
				totalPriceView.setText("" + getTwoDecimal(totalPri));
				totalPriceView.postInvalidate();
				curTotal.setText("" + getTwoDecimal(now * price));
				curTotal.postInvalidate();
				beforeText = now;
			}
		}
	}

	class GoodsNumberEditListener implements OnFocusChangeListener {
		private int position;
		private ShopCar shopCar;
		private TextView curTotal;
		private int before;

		GoodsNumberEditListener(int pos, final TextView total) {
			position = pos;
			this.shopCar = (ShopCar) getItem(position);
			this.curTotal = total;
		}

		public void onFocusChange(View v, boolean hasFocus) {
			EditText temp = (EditText) v;
			String s = temp.getText().toString();
			if (!hasFocus) {
				int now = 0;
				if (!s.equals("")) {
					now = Integer.parseInt(s.trim());
				} else {
					((EditText) v).setText("0");
				}
				if (now != cartInfoList.get(position).getCartInfo()
						.getGoodsNumber()) {
					// shopCar.getCartInfo().setGoodsNumber(now);
					// CartListAdapter.this.getItem(position).getCartInfo().setGoodsNumber(now);
					cartInfoList.get(position).getCartInfo()
							.setGoodsNumber(now);
					int totalNum = Integer.parseInt(totalNumView.getText()
							.toString().trim());
					totalNum = totalNum - before + now;
					double totalPri = Double.parseDouble(totalPriceView
							.getText().toString().trim());
					totalPri = totalPri + (now - before)
							* shopCar.getCartInfo().getGoodsPrice();
					totalNumView.setText("" + totalNum);
					totalNumView.postInvalidate();
					totalPriceView.setText("" + getTwoDecimal(totalPri));
					totalPriceView.postInvalidate();
					curTotal.setText(""
							+ getTwoDecimal(now
									* shopCar.getCartInfo().getGoodsPrice()));
					curTotal.postInvalidate();
					// CartListAdapter.this.notifyDataSetChanged();
				}
			} else {
				if (!s.equals("")) {
					before = Integer.parseInt(s.trim());
				}
			}
		}
	}

	private double getTwoDecimal(double d) {
		BigDecimal bd = new BigDecimal(d);
		double result = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		return result;
	}

	class lvButtonListener implements OnClickListener {
		private int position;

		lvButtonListener(int pos) {
			position = pos;
		}

		public void onClick(View v) {
			int vid = v.getId();
			DeleteFavoriteListAsync deleteFavoriteListAsync = new DeleteFavoriteListAsync(
					CartListAdapter.this.context, position);
			deleteFavoriteListAsync.execute(cartInfoList.get(position));
		}
	}

	public int getCount() {
		// TODO Auto-generated method stub
		return cartInfoList.size();
	}

	public ShopCar getItem(int position) {
		// TODO Auto-generated method stub
		return cartInfoList.get(position);
	}

	public long getItemId(int position) {
		return 0;
	}
}
